package cn.picclife.mwx.manager.sys.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.picclife.mwx.manager.sys.model.bo.DataResponse;
import cn.picclife.mwx.manager.sys.model.bo.SaveCollectRequest;
import cn.picclife.mwx.manager.sys.service.CollectDataService;
import cn.picclife.mwx.manager.sys.service.DownLoadFile;
import cn.picclife.mwx.manager.util.RedisUtil;
import cn.picclife.mwx.manager.util.enums.ResponseStatusEnum;

@Service
public class DownLoadFileImpl implements DownLoadFile {

	private static final Log log = LogFactory.getLog(DownLoadFileImpl.class);
	
	@Resource(name = "redisCache")
	private RedisUtil redisUtil;

	@Autowired
	private CollectDataService collectDataServiceImpl;


	@Async 
	@Override
	public void downLoadFile(List<String> reList, String filederpath, String uuid, List<String> recordList, long time) {
		log.info("获取路径数量:" + reList.size());
		// 记录开始下载的时间
		long begin_time = new Date().getTime();
		List<String> linkArrayNew = new ArrayList<String>();
		for (int i = 0; i < reList.size(); i++) {
			String url = reList.get(i);
			//获取到url地址https://ws-test.pc.ehuatai.com/htmart-console/api/commom/image/querypicture?picture=xsc00HT201906-0c9a20877eea4a598b21882ac5ee1b72.jpg
			if (!url.contains("/api/commom/image/querypicture") && url.indexOf("?")>-1 ) {
				//url地址无/api/commom/image/querypicture并且存在？就除去？后面的？号及其内容
				url = url.substring(0, url.indexOf("?"));
			}
			// 创建一个URL链接
			log.info(Thread.currentThread().getId()+"====文件全路径为：" + url);
			FileOutputStream fos = null;
			InputStream in = null;
			try {
				URL fileurl = new URL(url);
				// 获取连接
				URLConnection conn = fileurl.openConnection();
				// 设置超时时间 10S
				conn.setConnectTimeout(10000);  
				conn.setReadTimeout(10000); 
				in = conn.getInputStream();
				if (url.contains("/api/commom/image/querypicture")) {
                	//地址需要将？和 = 替换成/
                    url=url.replaceAll("[?,=]", "_");
				}
				// 获取文件全路径
				String fileName = url;
				// 获取文件名
				// mod by wzd begin
				// String filepath = filederpath + fileName.substring(fileName.indexOf("/") + 16, fileName.lastIndexOf("/") + 1);
				int num = url.indexOf("//") + 2;
				num = url.indexOf("/", num);
				// num = url.indexOf("/", num + 1);
				String filepath = filederpath;
				if(url.lastIndexOf("/")==num) {
					filepath = filederpath ;
				}else {
					filepath = filederpath + url.substring(num + 1, url.lastIndexOf("/"));
				}
				 
				//mod by wzd end
				fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
				log.info("开始下载>>>");
				// 创建文件路径
				File filePath = new File(filepath);
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				String newFileP = filepath +"/"+ fileName;
				linkArrayNew.add(newFileP);
				log.info("文件保存地址:" + newFileP);
				fos = new FileOutputStream(new File(newFileP));
				byte[] by = new byte[1024*10];
				int len = 0;
				while ((len = in.read(by))>0){
					fos.write(by,0,len);
				}
			} catch (Exception e) {
				log.error(e);
			}finally{
				if(fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						log.error(e);
					}
				}
				if(in != null){
					try {
						in.close();
					} catch (IOException e) {
						log.error(e);
					}
				}
			}
		}
		long end_time = new Date().getTime();
		long seconds = (end_time - begin_time) / 1000;
		long minutes = seconds / 60;
		long second = seconds % 60;
		log.info("下载完成,用时：" + minutes + "分" + second + "秒");
		
	}

	/**
	 * 异步对比js\css
	 * @param req
	 */
	@Async
	public void compareAnddownload(SaveCollectRequest req){
		
		DataResponse res =  collectDataServiceImpl.compareJS(req);//======比较js==
		//如果js比对为下载则增加版本
		log.info("异步比对js返回结果:"+JSONObject.toJSONString(res).toString());
		if(ResponseStatusEnum.UPDATE_JS.getCode().equals(res.getCode())) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String todayStr = sdf.format(new Date());
			String key = "v2"+todayStr + req.getSystemCode()+"Uid";
			String newVersionId = UUID.randomUUID().toString();// 最新versionUUID
			String uuid = redisUtil.getStr(key);
			if(uuid!=null&&uuid.trim().length()>0) {
				newVersionId = uuid;
			}else {
				redisUtil.setStr(key, newVersionId);
				redisUtil.setExpire(key, 24*60*60*1000);	
			}


			//newVersionId====>system
			collectDataServiceImpl.downloadJS(req, newVersionId);
		}
	}
	
	/**
	 * 
	 * 异步下载山东城商联盟静态资源
	 */
	@Async
	public void asyncDown(SaveCollectRequest req) {
		collectDataServiceImpl.unZipStatic(req);
	}
}
